var devClient={};
try {
    var devClient = {
        config: {
            appName: "hhRemoteAssist",
            kurentUrl: "wss://wss.hhdata.cn:8433/kurento",
            kmsPeerOptions: {
                configuration: {
                    "iceServers": [
                        {
                            urls: "stun:223.68.161.139:3478"
                        },
                        {
                            urls: ["turn:223.68.161.139:3478"],
                            username: "kurento",
                            credential: "kurento"
                        }
                    ]
                },
                mediaConstraints: {
                    audio: true,
                    video: {width: {exact: 1280}, height: {exact: 720}}
                },
                localVideo: null,
                remoteVideo: null
            },
            kmsPeerTypes: {
                send: kurentoUtils.WebRtcPeer.WebRtcPeerSendonly,
                rec: kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly,
                sendRec: kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv
            },
            apiUrl: "https://wss.hhdata.cn:20022/devapi/"
        },
        callApi: function (ac, ps, callback) {
            var me = devClient;
            try {
                var url = me.config.apiUrl + ac + "?tmrnd=" + (new Date()).getTime().toString();
                /*
                $.post( url , ps , function (res) {
                        try{
                            var result = JSON.parse(res);
                            hhls.callBack(callback , result);
                        }
                        catch (er0) {
                            console.log(er0);
                        }
                    } );
                 */
                $.ajax({
                    url: url,
                    data: ps,
                    //type:"POST",
                    //contentType:"JSON",
                    success: function (res) {
                        try {
                            var result = JSON.parse(res);
                            hhls.callBack(callback, result);
                        } catch (er0) {
                            console.log(er0);
                        }
                    },
                    error: function (errRes) {
                        try {
                            hhls.callBack(callback, errRes);
                        } catch (er0) {

                        }
                    }
                })
            } catch (e) {
                console.log(e)
            }
        },
        dbQuery: function (key, ps, callback) {
            var me = devClient;
            try {
                var ac = "dbQuery";
                var psJson = JSON.stringify(ps);
                var psData = {
                    appName: me.config.appName,
                    key: key,
                    ps: psJson
                };
                me.callApi(ac, psData, callback);
            } catch (e) {
                console.log(e)
            }
        },
        callBack: function (callback, p0, p1, p2) {
            var me = devClient;
            try {
                if (callback && callback != null) {
                    callback(p0, p1, p2);
                }
            } catch (e) {
                console.log(e)
            }
        },
        openWsClient: function (wsUrl, onOpen, onClose, onMsg) {
            var me = devClient;
            var wsClient = null;
            try {
                var ws = new WebSocket(wsUrl);
                ws.onopen = function () {
                    //当WebSocket创建成功时，触发onopen事件
                    console.log("wss is openned!");
                };
                ws.onerror = function () {
                    try {
                        ws.close();
                    } catch (e1) {
                        console.log(e1);
                    }
                };
                ws.onclose = function () {
                    try {
                        me.callBack(onClose, ws);
                    } catch (e1) {
                        console.log(e1);
                    }
                };
                ws.onmessage = function (e) {
                    try {
                        var msg = JSON.parse(e.data);
                        if (msg.msgId == "onGetWsId") {
                            ws.wsId = msg.msgBody.wsId;
                            me.callBack(onOpen, ws);
                        } else if (onMsg) {
                            me.callBack(onMsg, ws, msg);
                        }
                    } catch (err) {
                        console.log(err);
                    }
                };
                wsClient = ws;
            } catch (e) {
                console.log(e)
            }
            return wsClient;
        },
        kmsGetClient: function (callback) {
            var me = this;
            try {
                if (me.kurentClient) {
                    me.callBack(callback, me.kurentClient);
                } else {
                    kurentoClient(me.config.kurentUrl, function (error, client) {
                        if (client) {
                            me.kurentClient = client;
                        }
                        me.callBack(callback, client);
                    });
                }
            } catch (er) {
                console.log(er);
            }
        },
        kmsBindPeerAndEndpoint: function (peer, endpoint, callback) {
            var me = this;
            try {
                var setCandidateEvent = function (peer, endpoint) {
                    try {
                        if (peer && endpoint) {
                            endpoint.on('OnIceCandidate', function (event) {
                                var candidate = event.candidate;
                                peer.addIceCandidate(candidate);
                                console.log('candidate w->p')
                            });
                            peer.on('icecandidate', function (candidate) {
                                var iceCandidate = kurentoClient.register.complexTypes.IceCandidate(candidate);
                                endpoint.addIceCandidate(iceCandidate);
                                console.log('candidate p->w')

                            });
                        }
                    } catch (e) {
                        ;
                    }
                }
                if (endpoint && peer) {
                    peer.generateOffer(function (errorPeerGenerateOffer, sdpOffer) {
                        if (errorPeerGenerateOffer && callback) {
                            callback(errorPeerGenerateOffer, null);
                        } else {
                            endpoint.processOffer(sdpOffer, function (errorSdpOffer, sdpAnswer) {
                                if (errorSdpOffer && callback) {
                                    console.log("process sdpOffer error.", errorSdpOffer)
                                    callback(errorSdpOffer, null);
                                } else {
                                    setCandidateEvent(peer, endpoint);
                                    peer.processAnswer(sdpAnswer);
                                    endpoint.gatherCandidates(function (errorGatherCandidates) {
                                        if (errorGatherCandidates && callback) {
                                            console.log('webRtcPoint gatherCandidates error.', errorGatherCandidates)
                                            callback(errorGatherCandidates, null);
                                        } else {
                                            peer.endpoint = endpoint;
                                            endpoint.peer = peer;
                                            setCandidateEvent(peer, endpoint);
                                            if (callback) {
                                                callback(null, {endpoint: endpoint, peer: peer});
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    });
                } else {
                    if (callback) {
                        callback({error: "endPoint or peer is null."}, null);
                    }
                }
            } catch (er) {
                console.log(er, "bindPeerAndEndpoint error.");
            }
        },
        kmsGetAvDevices: function (callback) {
            var me = this;
            try {
                var res = {};
                /*
                        navigator.mediaDevices.enumerateDevices(function (devs) {

                            for( var i=0;i<devs.length;i++){
                                var item = devs[i];
                                if( !res[item.kind]){
                                    res[item.kind]=[]
                                }
                                res[item.kind].push(item);
                            }
                            console.log(res);
                            if (callback){
                                callback({error: null, devices:res});
                            }
                        });
                */
                navigator.mediaDevices.enumerateDevices().then(function (devs) {
                    for (var i = 0; i < devs.length; i++) {
                        var item = devs[i];
                        if (!res[item.kind]) {
                            res[item.kind] = []
                        }
                        res[item.kind].push(item);
                    }
                    console.log(res);
                    if (callback) {
                        callback({error: null, devices: res});
                    }
                });
            } catch (er) {
                console.log(er, "createPeer error.");
            }
        },
        kmsChangeCamera: function (peer, newCameraDeviceId, callback) {
            var me = this;
            try {
                var result = {error: null, res: null};
                if (window.rtcVideoStream) {
                    window.rtcVideoStream.getTracks().forEach(track => {
                        if (track.kind == "video") {
                            track.stop();
                        }
                    });
                }

                var constraints = {video: {deviceId: newCameraDeviceId, height: {exact: 720}, width: {exact: 1280}}};
                navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
                    window.rtcVideoStream = stream;
                    peer.localVideo.srcObject = stream;
                    let videoTrack = stream.getVideoTracks()[0];
                    sender = peer.peerConnection.getSenders().find(function (s) {
                        return s.track.kind == videoTrack.kind;
                    });
                    sender.replaceTrack(videoTrack);

                });


                /*
                if (window.rtcVideoStream) {
                    window.rtcVideoStream.getTracks().forEach(track => {
                        track.stop();
                    });
                }
                var constraints = {
                    video: {
                        deviceId: newCameraDeviceId ,
                        height:{
                            exact:720
                        },
                        width:{
                            exact:1280
                        },
                        frameRate :30
                    }
                };
                constraints = {video: {deviceId: newCameraDeviceId}};
                var sender = null;
                navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
                    try{
                        if( stream){
                            peer.localVideo.srcObject = stream;
                            let videoTrack = stream.getVideoTracks()[0];
                            sender = peer.peerConnection.getSenders().find(function (s) {
                                return s.track.kind == videoTrack.kind;
                            });
                            sender.replaceTrack(videoTrack);
                            result.res = constraints;
                            if( callback){
                                callback(result);
                            }
                        }
                        else{
                            if( callback){
                                result.error = "stream is null";
                                callback(result);
                            }
                        }
                    }
                    catch (er) {
                        console.log(er);
                    }
                }).catch(function (ee) {
                    alert(JSON.stringify(ee))
                });

                 */
            } catch (er) {
                alert(JSON.stringify(er))
                console.log(er);
            }
        },
        kmsShareScreen: function (peer, callback) {
            var me = this;
            try {
                var screenConstraints = {video: {width: {max: 1280}, height: {max: 720}}, audio: true};
                if (navigator.mediaDevices.getDisplayMedia) {
                    //navigator.mediaDevices.getDisplayMedia({video:true}).then(
                    navigator.mediaDevices.getDisplayMedia(screenConstraints).then(
                        function (stream) {
                            let videoTrack = stream.getVideoTracks()[0];
                            peer.localVideo.srcObject = stream;
                            sender = peer.peerConnection.getSenders().find(function (s) {
                                return s.track.kind == videoTrack.kind;
                            });
                            sender.track.stop();
                            sender.replaceTrack(videoTrack);
                            if (callback) {
                                callback();
                            }
                        }
                    )
                }
            } catch (er) {
                console.log(er);
            }
        },
        runLoop: function (arrItems, action, onItem, onAll) {
            var me = this;
            try {
                if (arrItems && arrItems.length > 0) {
                    var index = 0;
                    var runSelf = function () {
                        if (index < arrItems.length) {
                            var itemData = arrItems[index];
                            try {
                                action(itemData, function () {
                                    try {
                                        me.callBack(onItem, itemData, index, arrItems);
                                        index++;
                                        runSelf();
                                    } catch (e1) {
                                        console.log(e1);
                                    }
                                })
                            } catch (er) {
                                console.log(er);
                            }
                        } else {
                            me.callBack(onAll);
                        }
                    }
                    runSelf();
                } else {
                    me.callBack(onAll);
                }
            } catch (e) {
                console.log(e);
            }
        }
    }
}
catch (e) {
    alert(e);
}